package com.mocha.mybatis.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.mocha.common.core.MochaHeader;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 自动填充
 * @author: songkui
 * @date: 2022/3/10 16:56
 */
@Slf4j
public class AuditMetaObjectHandler implements MetaObjectHandler {

    public static final String CREATE_TIME = "createTime";
    public static final String UPDATE_TIME = "updateTime";
    public static final String CREATOR_ID = "creatorId";
    public static final String UPDATER_ID = "updaterId";

    @Autowired(required = false)
    protected HttpServletRequest request;

    @Override
    public void insertFill(MetaObject metaObject) {

        Date now = new Date();
        if (metaObject.hasSetter(CREATE_TIME)) {
            this.setFieldValByName(CREATE_TIME, now, metaObject);
        }
        if (metaObject.hasSetter(UPDATE_TIME)) {
            this.setFieldValByName(UPDATE_TIME, now, metaObject);
        }

        long userId = 1;
        if (metaObject.hasSetter(CREATOR_ID)) {
            this.setFieldValByName(CREATOR_ID, userId, metaObject);
        }
        if (metaObject.hasSetter(UPDATER_ID)) {
            this.setFieldValByName(UPDATER_ID, userId, metaObject);
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasSetter(UPDATE_TIME)) {
            this.setFieldValByName(UPDATE_TIME, new Date(), metaObject);
        }
        if (metaObject.hasSetter(UPDATER_ID)) {
            long userId = 1;
            this.setFieldValByName(UPDATER_ID, userId, metaObject);
        }
    }

}
